"""
重返未来1999主函数代码
"""

from detect_object import *
from detect_card import *
from decision import Card
from mouse import *
import pyautogui

global inning # 回合次数(全局变量)

"""
get_phone_frame获取手机图像函数
返回
    返回获取到的手机图像
"""
def get_phone_frame():
    image = pyautogui.screenshot(region=[960, 50, 960, 430])#此处需自行更改坐标
    image = cv2.cvtColor(np.asarray(image), cv2.COLOR_RGB2BGR)
    return image
"""
get_card_information获取卡牌信息函数
传参说明
    image---传入图像
返回
    函数主要调用detect_card中的函数，对卡牌信息整合并返回
    card_level_list---卡牌等级列表
    ownership_list---卡牌所属人物列表
    card_attribute_list---卡牌底部文字信息列表
"""
def get_card_information(image):
    # 分割图像分别处理
    ROI_Image = image[318:429, 401:930]
    Text_Image = image[416:429, 384:970]
    Level_Image = image[318:330, 401:930]
    Ownership_Image = image[330:416, 401:930]

    Text_Image = cv2.resize(Text_Image, None, fx=2, fy=2)
    Level_Image = cv2.resize(Level_Image, None, fx=2, fy=2)
    Text_Image = cv2.cvtColor(Text_Image, cv2.COLOR_BGR2GRAY)
    t1, Text_Image = cv2.threshold(Text_Image, 25, 200, cv2.THRESH_BINARY) #对图片进行二值化,提高文字识别率

    card_level_list = Get_Card_Level(Level_Image)

    ownership_list = detect_owner_new(Ownership_Image)

    card_attribute_list = Get_Card_Text_Information(Text_Image)

    return (card_level_list,ownership_list,card_attribute_list)

"""
show_alive_situation显示人物存活状态列表
传参说明
    num---对应人物下标
返回
    返回字符串
"""
def show_alive_situation(num):
    if num == 4:
        return "红弩箭存活"
    elif num == 5:
        return "远旅存活"
    elif num == 6:
        return "槲寄生存活"
"""
get_person_information获取人物信息函数
传参说明
    image---传入图像
返回
    enemy_seeking---敌方坐标信息
"""
def get_person_information(image):
    enemy_information = Detect_Enemy(image, 640, 0.5, device, torch_model)
    character_information = Detect_Character(image, 640, 0.5, device, torch_model)

    enemy_seeking = []

    print("检测到还剩",len(enemy_information),"个敌人")
    for i in range(0, len(enemy_information)):
        #获取敌方坐标
        xmin = enemy_information[i][0]
        ymin = enemy_information[i][1]
        xmax = enemy_information[i][2]
        ymax = enemy_information[i][3]
        enemy_class = enemy_information[i][4]

        enemy_seeking.append([enemy_class,xmin,ymin,xmax,ymax])#存入敌方坐标信息
        image = cv2.rectangle(image, (xmin, ymax), (xmax, ymin), (0, 0, 255), 2)#画框
    for j in range(0, len(character_information)):

        xmin = character_information[j][0]
        ymin = character_information[j][1]
        xmax = character_information[j][2]
        ymax = character_information[j][3]
        character_class = character_information[j][4]

        print(show_alive_situation(character_class))#显示我方人物存活状态

        image = cv2.rectangle(image, (xmin, ymax), (xmax, ymin), (255, 0, 0), 2)#画框
    return enemy_seeking

"""
Select_Enemy索敌函数
传参说明
    enemy_seeking---敌方信息列表
该函数根据索敌优先级判定，根据坐标运算出电脑鼠标点击位置完成索敌
点击敌人用到了mouse程序里的函数
"""
def Select_Enemy(enemy_seeking):
    center_position = (0,0)

    for i in range(0,len(enemy_seeking)):
        if enemy_seeking[i][0] == 2:
            center_position = (enemy_seeking[i][1]+(enemy_seeking[i][3]-enemy_seeking[i][1])/2,
                               enemy_seeking[i][2]+(enemy_seeking[i][4]-enemy_seeking[i][2])/2)
            break
    if center_position == (0,0):
        center_position = (enemy_seeking[0][1]+(enemy_seeking[0][3]-enemy_seeking[0][1])/2,
                               enemy_seeking[0][2]+(enemy_seeking[0][4]-enemy_seeking[0][2])/2)
    print(center_position)
    click_position(center_position[0],center_position[1])#点击敌人

"""
<--下面就是主函数调用其他文件里的函数做总控制的代码-->
"""
if __name__ == "__main__":
    inning = 1
    device, torch_model = torch_init("cpu", "/Users/a1/Desktop/Game1999/yolov5-6.2",
                                     "/Users/a1/Desktop/Game1999/exp3/weights/best.pt")  # 初始化设置
    image = get_phone_frame()
    #先显示截取到的第一张图片
    cv2.imshow("image", image)
    cv2.waitKey(0)#等待键盘按下
    while True:
        image = get_phone_frame()

        #重复识别"最初的速度"
        dot_bool = Detect_Cost(image,640,device,0.4,torch_model)
        print(dot_bool)
        #如果识别到
        if dot_bool == True:
            print("Start to detect enemy")
            time.sleep(0.3)
            enemy_seeking = get_person_information(image)
            Select_Enemy(enemy_seeking)#控制安卓机索敌

            #获取卡牌信息
            card_information_list = get_card_information(image)
            card_level_list = card_information_list[0]
            ownership_list = card_information_list[1]
            card_attribute_list = card_information_list[2]

            #显示识别效果
            cv2.imshow("image", image)
            cv2.waitKey(1)

            print(card_level_list, "\n", ownership_list)
            """
            下面的代码是容错处理的，用来应对卡牌识别不到的问题
            本人时间紧这部分还没好好想怎么写，欢迎大家来发issues互相交流一下
            """
            if len(card_level_list) == 8:
                card_level_list.pop(7)
            if len(card_level_list) > 7:
                print("delete")
                for i in range(7,len(card_level_list)-1):
                    card_level_list.pop(i)
                print(card_level_list)
            if len(card_level_list) < 7:
                print("plus")
                for i in range(0,7-len(card_level_list)):
                    card_level_list.append(1)
            #识别到7张卡牌才开始对策
            if len(card_level_list) == 7 and len(ownership_list) == 7:
                print(card_level_list, "\n", ownership_list, "\n", card_attribute_list)
                card = Card()
                #尝试
                try:
                    #选择最佳卡牌组合
                    operation = card.choose_best(ownership_list, card_level_list)
                    print(operation.split(" ")[0],operation.split(" ")[1],operation.split(" ")[2])
                    #出牌
                    click_card(int(operation.split(" ")[0]))
                    time.sleep(0.8)
                    click_card(int(operation.split(" ")[1]))
                    time.sleep(0.8)
                    click_card(int(operation.split(" ")[2]))
                    print("Done")
                    #防止鼠标影响下一帧的识别，将鼠标移至中心位置
                    click_card("center")
                    dot_bool = False
                #如果出错
                except:
                    print("ERROR")
                    click_card(1)
                    time.sleep(0.8)
                    click_card(2)
                    time.sleep(0.8)
                    click_card(3)
                    dot_bool = False
            else:
                dot_bool = False
        elif dot_bool == False:
            print("wait......")
        inning += 1 # 回合加一

